// import {getUserInfoApi} from "@/api/mock"
import {loginApi, logoutApi, getUserInfoApi} from "@/api/user"
import router from "@/router"
import {anyRouter, asyncRouter, constRouter} from "@/router/route"
import local, {
    GET_REFRESH_TOKEN,
    GETTOKEN,
    GETUSERINFO,
    REMOVETOKEN,
    SETTOKEN,
    SET_REFRESH_TOKEN,
    SETUSERINFO,
} from "@/utils/local"
import cloneDeep from "lodash/cloneDeep"
import {defineStore} from "pinia"
import {nextTick, ref} from "vue"
import {$t} from '@/utils/i18n'

// import type {RouteLocationOptions} from "vue-router"

interface loginParams {
    // username?: string
    // password?: number
    // phone: string
    // code: string
    regionCode: number,
    mobile: string,
    verifyCode: string,
}

interface userParams {
    userId?: number
    phone?: string
    mobile?: string
    regionCode?: number
}

export const useUserStore = defineStore(
    "userStore",
    () => {
        /***
         * @登录
         */
        const token = ref(GETTOKEN())
        const userinfo = ref(GETUSERINFO() as userParams)
        const flag = ref(false)

        // 用户登录
        const loginUp = async (loginParams: loginParams) => {
            const res: any = await loginApi(loginParams)
            if (res.code === 200) {
                const data: any = res.data
                token.value = data.access_token
                userinfo.value = {
                    phone: loginParams.mobile,
                    regionCode: loginParams.regionCode,
                    mobile: data.Mobile,
                    userId: data.UserID,
                }
                SETTOKEN(data.AccessToken, data.ExpiresIn);
                SET_REFRESH_TOKEN(data.RefreshToken);
                SETUSERINFO(userinfo.value);
                // await getUserInfo()
                return $t('messageBox.loginSuccess')
            } else {
                return Promise.reject(new Error(res.msg))
            }
        }
        /**
         * @路由
         */

            // 路由表
        const routerMenuList = ref([] as any)
        // // 权限路过滤
        const filterRoute = (routes: any, asyncRoute: any) => {
            return asyncRoute.filter((route: any) => {
                if (routes.includes(route.name)) {
                    if (route.children && route.children.length > 0) {
                        route.children = filterRoute(routes, route.children)
                    }
                    return true
                }
            })
        }

        // 所有异步路由
        const getUserInfo = async () => {
            if (!GET_REFRESH_TOKEN()) {
                return false;
            }
            const res: any = await getUserInfoApi()
            if (res.code === 200) {
                const data = res.data;
                SETUSERINFO(data);
                SETTOKEN(data.AccessToken, data.ExpiresIn);
                SET_REFRESH_TOKEN(data.RefreshToken);
                await nextTick(() => {
                    userinfo.value = GETUSERINFO();
                });
                // initRoutes()
            }
            return res.code === 200
        }

        const initRoutes = () => {
            // 异步路由
            const lastAsyncRoute = cloneDeep(asyncRouter)

            //常量路由，异步路由，任意路由（路由表,侧边栏）
            routerMenuList.value = [...constRouter, ...lastAsyncRoute, ...anyRouter]

            // 异步路由+任意路由
            const asyncRoutes = [...lastAsyncRoute, ...anyRouter]
            // 添加路由
            asyncRoutes.forEach((item: any) => {
                router.addRoute(item)
            })

            // console.log(router.getRoutes())
        }
        initRoutes()

        // 重置路由
        const resetRoutes = () => {
            //移除所有路由
            routerMenuList.value.forEach((route: any) => {
                router.removeRoute(route.name)
            })
        }

        // 退出登录
        const loginOut = () => {
            // try {
            //     await logoutApi();
            // } catch (e) {
            //     console.log(e);
            // }
            REMOVETOKEN()
            userinfo.value = {}
            routerMenuList.value = []
            resetRoutes()
        }

        return {
            flag,
            token,
            routerMenuList,
            userinfo,
            loginUp,
            loginOut,
            getUserInfo,
            resetRoutes,
        }
    },
    {
        // persist: true,
        persist: {
            key: "userStore",
            pick: ["flag", "userinfo"],
        },
    },
)
